from flask import render_template,redirect, request
from flask.blueprints import Blueprint
from Web.Pojo.User import User
from Web.Pojo.Post import Post
from Web.Pojo.Message import Message
from Web.Pojo.ReplyToPost import ReplyToPost
from Web.Pojo.ViewObject import ViewObject
from Web.Service import WebBaseService,XssService,SessionService
import datetime
from __init__ import db

usercenter = Blueprint('usercenter', __name__)

########################################################
#                                                   登陆
########################################################
@usercenter.route("/user/login.html",methods=['GET'])
def postArticlePage5():
    currentUser = SessionService.get( "user" )

    if currentUser == None:
        return render_template( '/bbs/user/login.html' )
    else:
        return redirect("/bbs", code=302, Response=None)

#登陆
@usercenter.route("/user/login.html",methods=['POST'])
def postArticlePage6():
    user = WebBaseService.requestParamToInstance( User( ) , request.values.dicts[ 1 ] )
    ret = -1
    if User.query.filter( User.mail == user.mail).filter(User.password == user.password ).count() > 0:
        ret = 0

    if ret == -1:
        return "{\"status\":-1,\"msg\":\"\",\"code\":\"登陆失败\"}"
    else:
        user = User.query.filter( User.mail == user.mail).first()
        print(user)
        SessionService.set("user",user)
        return "{\"status\":0,\"msg\":\"\",\"code\":\"登陆成功\"}"

#logout
@usercenter.route("/logout",methods=['GET'])
def postArticlePage62():
    SessionService.set("user",None)
    return redirect("/bbs")
########################################################
#                                                   注册
########################################################
@usercenter.route("/user/reg.html",methods=['GET'])
def postArticlePage7():
    return render_template( '/bbs/user/reg.html' )

#注册
@usercenter.route("/user/reg.html",methods=['POST'])
def postArticlePage8():
    user = WebBaseService.requestParamToInstance( User( ) , request.values.dicts[ 1 ] )
    ret = -1

    if User.query.filter(User.mail==user.mail or User.nickname==user.nickname)==0:
        if db.session.add( user ) > 0:
            ret = 0

    if ret==-1:
        return "{\"status\":-1,\"msg\":\"\",\"code\":\"注册失败 用户已存在\"}"
    else:
        return "{\"status\":0,\"msg\":\"\",\"code\":\"注册成功\"}"


########################################################
#                                                   用户中心
########################################################
#用户主页
@usercenter.route("user/index.html")
def postArticlePage9():
    currentUser = SessionService.get( "user" )

    if currentUser!=None:
        articleList = Post.query.filter( Post.authorid == currentUser.id ).limit( 50 ).all( )
        replyList = ReplyToPost.query.filter( ReplyToPost.authorid == currentUser.id ).limit( 50 ).all( )
        return render_template( '/bbs/user/index.html',user=currentUser,articleList=articleList,replyList=replyList)
    else:
        return redirect("/bbs")

#用户设置
@usercenter.route("user/set.html")
def postArticlePage10():
    user = SessionService.get( "user" )
    if user!=None:
        return render_template( '/bbs/user/set.html' ,user= SessionService.get( "user" ))
    else:
        return redirect("/bbs")

#消息页面
@usercenter.route("user/message.html")
def postArticlePage11():
    currentUser = SessionService.get( "user" )
    if currentUser!=None:
        messages = Message.query.filter(Message.recverid == currentUser.id).limit(30).all()
        return render_template( '/bbs/user/message.html', messages=messages)
    else:
        return redirect("/bbs")

#删除消息
@usercenter.route("message/remove/",methods=['POST'])
def postArticlePage112():
    currentUser = SessionService.get( "user" )
    message = WebBaseService.requestParamToInstance(ReplyToPost( ),request.values.dicts[ 1 ] )
    if currentUser!=None :
        message = Message.query.filter(Message.id == message.id).first()
        print(message)
        if message == None or message.recverid != currentUser.id:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"删除失败\"}"
        db.session.delete(message)
        return "{\"status\":0,\"msg\":\"\",\"code\":\"删除成功\"}"
    else:
        return "{\"status\":-1,\"msg\":\"\",\"code\":\"删除失败\"}"

#用户主页
@usercenter.route("user/home.html")
def postArticlePage12():
    currentUser = SessionService.get("user")
    visitUserId = request.args.get( "id" )
    articleList = []
    replyList=[]
    viewObject=[]

    #查询不到被访问用户
    if visitUserId==None or Post.query.filter(User.id==visitUserId).count()==0:
        #变为访问自己空间
        if (currentUser != None):
            visitUserId = currentUser.id
        else:
            return redirect("/bbs")

    #发帖纪录
    articleList = Post.query.filter(Post.authorid == visitUserId).limit(20).all()
    #回帖纪录
    replyList = ReplyToPost.query.filter(ReplyToPost.authorid==visitUserId).limit(5).all()
    for reply in replyList:
        reply.content = XssService.defxss( WebBaseService.jiexiToHtml( reply.content ) )
        viewObject.append( ViewObject( A=reply , B=Post.query.filter( Post.id == reply.linkPostId ).first( )) )

    return render_template( '/bbs/user/home.html',articleList=articleList,viewObject=viewObject,user=User.query.filter(User.id==visitUserId).first())

#修改信息
@usercenter.route("user/set.html",methods=['POST'])
def postArticlePage113():
    currentUser = SessionService.get("user")
    updateUser = WebBaseService.requestParamToInstance( User( ) , request.values.dicts[ 1 ] )

    if  currentUser!=None:
        if updateUser.avator!=None or updateUser.qq!=None or updateUser.sign!=None:
            User.query.filter(User.id==currentUser.id).update({User.avator:updateUser.avator,User.qq:updateUser.qq,User.sign:updateUser.sign})
            currentUser.avator = updateUser.avator
            currentUser.qq = updateUser.qq
            currentUser.sign = updateUser.sign
            SessionService.set("user",currentUser)
        elif updateUser.password!=None:
            if request.form['nowpass']!=currentUser.password:
                return "{\"status\":-1,\"msg\":\"\",\"code\":\"旧密码不对\"}"
            User.query.filter( User.id == currentUser.id ).update({User.password: updateUser.password} )
            currentUser.password = updateUser.password
            SessionService.set( "user" , currentUser )
        else:
            pass
        return "{\"status\":0,\"msg\":\"\",\"code\":\"修改成功\"}"
    else:
        return "{\"status\":-2,\"msg\":\"\",\"code\":\"未登录\"}"


 ########################################################
#                                                   签到
########################################################
@usercenter.route("sign/in",methods=['POST'])
def postArticlePage14():
    currentUser = SessionService.get("user")
    signOnceCoin=5

    if currentUser == None:
        # 用户未登录
        return "{\"status\":-2,\"msg\":\"\",\"code\":\"未登录\"}"
    elif (datetime.datetime.now( ).day == currentUser.lastsign.day):
        # 用户已签到
        return "{\"status\":-3,\"msg\":\"\",\"code\":\"已签到\"}"
    else:
        currentUser.coin+=signOnceCoin
        currentUser.lastsign = datetime.datetime.now()
        SessionService.set("user",currentUser)
        User.query.filter(User.id==currentUser.id).update({User.coin:currentUser.coin,User.lastsign:currentUser.lastsign})
        return "{\"status\":0,\"msg\":\"\",\"code\":\"签到成功\"}"

########################################################
#                                                   点赞
########################################################
@usercenter.route("api/jieda-zan/",methods=['POST'])
def postArticlePage15():
    currentUser = SessionService.get("user")
    replyToPost = WebBaseService.requestParamToInstance( ReplyToPost( ) , request.values.dicts[ 1 ] )

    if currentUser == None:
        # 用户未登录
        return "{\"status\":-2,\"msg\":\"\",\"code\":\"未登录\"}"
    else:
        reply = ReplyToPost.query.filter(ReplyToPost.id == replyToPost.id).first()
        if reply!=None:
            ReplyToPost.query.filter( ReplyToPost.id == replyToPost.id ).update({ReplyToPost.point:reply.point+1})
            return "{\"status\":0,\"msg\":\"\",\"code\":\"点赞成功\"}"
        else:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"点赞失败\"}"

########################################################
#                                                   文章
########################################################
#删除
@usercenter.route("api/jie-delete/",methods=['POST'])
def postArticlePage16():
    currentUser = SessionService.get("user")
    post = WebBaseService.requestParamToInstance( Post( ) , request.values.dicts[ 1 ] )

    if currentUser == None:
        # 用户未登录
        return "{\"status\":-2,\"msg\":\"\",\"code\":\"未登录\"}"
    else:
        post = Post.query.filter(Post.id == post.id).first()
        if post!=None:
            if currentUser.id==post.id or currentUser.level>200:
                db.session.delete( post )
                return "{\"status\":0,\"msg\":\"\",\"code\":\"删除成功\"}"
            return "{\"status\":0,\"msg\":\"\",\"code\":\"禁止删除\"}"
        else:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"文章不存在\"}"

#置顶
@usercenter.route("api/jie-set/",methods=['POST'])
def postArticlePage162():
    currentUser = SessionService.get("user")
    post = WebBaseService.requestParamToInstance( Post( ) , request.values.dicts[ 1 ] )

    if currentUser == None:
        # 用户未登录
        return "{\"status\":-2,\"msg\":\"\",\"code\":\"未登录\"}"
    else:
        post = Post.query.filter(Post.id == post.id).first()
        if post!=None:
            if currentUser.level>200:
                Post.query.filter(Post.id == post.id).update({Post.topId: post.bankuai} )
                return "{\"status\":0,\"msg\":\"\",\"code\":\"置顶成功\"}"
            return "{\"status\":0,\"msg\":\"\",\"code\":\"置顶删除\"}"
        else:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"文章不存在\"}"